package com.demo2do.sms.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.entity.result.Result;
import com.demo2do.sms.entity.sms.SmsRequest;
import com.demo2do.sms.handler.SmsSender;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/sms")
public class SmsController {
    
    private static final Logger logger = LoggerFactory.getLogger(SmsController.class);
    
    @Autowired
    private SmsSender smsSender;
    
    /**
     * 
     * @param smsRequest
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult send(@RequestBody SmsRequest smsRequest) {
        
        HttpResult httpResult = new HttpResult();
        
        logger.trace("#send() with params mobile[{}], client[{}]", smsRequest.getMobiles(), smsRequest.getClient());
        
        if(smsRequest.isValid()) {
            
            // send message
            Result result = smsSender.send(smsRequest.getClient(), smsRequest.getMobiles(), smsRequest.getMessage());

            if(result.isValid()) {
                
                // directly return success
                httpResult.success().message("发送短信成功");
                
            } else {
                
                // return error message
                httpResult.fail("500").message(result.getMessage());
            }
            
        } else {
            httpResult.fail("400").message("请求参数校验错误");
        }
        
        return httpResult;
    }
}
